package com.ham.mud.commands;

import com.ham.mud.Colors;
import com.ham.mud.ServerConnection;
import com.ham.mud.TargetableService;
import com.ham.mud.characters.mobs.Mob;
import com.ham.mud.characters.player.Player;
import com.ham.mud.rooms.Room;
import com.ham.mud.rooms.RoomService;
import com.ham.mud.state.CombatState;
import com.ham.mud.state.PVPState;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hlucas on Jun 17, 2011 at 3:51:31 PM
 */
public class KillCommand extends PlayerCommand {
    @Override
    protected String getCommandName() {
        return "kill";
    }

    @Override
    public void execute(ServerConnection connection, String[] params) {
        if(params.length == 0) {
            connection.printSolo("Kill who?");
            return;
        }

        String target = params[0];
        if(target.equals("self")) {
            new SuicideCommand().execute(connection, new String[]{});
            return;
        }

        Player player = connection.getPlayer();
        int atX = player.getAtX();
        int atY = player.getAtY();
        Room room = RoomService.getRoom(player.getZone(), atX, atY);

        List<Mob> mobs = room.getMobs();
        Mob targetMob = (Mob) TargetableService.findTarget(target, mobs);
        if(targetMob != null) {
            if (targetMob.getMudClass() == null) {
                connection.printSolo("You cannot kill " + targetMob.getName());
                return;
            }
            connection.printSolo("You engage in vicious combat with " + targetMob.getName() + "!");
            room.printToOthers(player.getName() + " attacks " + targetMob.getName() + "!", connection);
            connection.changeState(new CombatState(connection, targetMob));
            return;
        }

        List<ServerConnection> others = room.getOtherConnections(connection);
        List<Player> players = new ArrayList<Player>();
        Map<String, ServerConnection> playerConnections = new HashMap<String, ServerConnection>();
        for(ServerConnection other : others) {
            Player otherPlayer = other.getPlayer();
            players.add(otherPlayer);
            playerConnections.put(otherPlayer.getName(), other);
        }

        Player targetPlayer = (Player) TargetableService.findTarget(target, players);
        if(targetPlayer == null) {
            connection.printSolo("There's nobody here by that name.");
            return;
        }

        ServerConnection other = playerConnections.get(targetPlayer.getName());
        other.printStart(Colors.NEW_LINE + player.getName() + " does the unthinkable and starts to attack you!");
        connection.println(Colors.NEW_LINE + "You do the unthinkable and start to attack " + targetPlayer.getName() + "!");

        connection.changeState(new PVPState(connection, other));
        other.changeState(new PVPState(other, connection));
    }
}
